<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Exemple de liste triable par glisser/déposer</title>
        <meta name="author" content="forresst" />
        <script src="../scripts_js/fonctions.js"></script>
        <script type="text/javascript" src="../scripts_js/XMLHttpRequest.js"></script>
        <script src="../scripts_js/jquery-1.10.0.min.js"></script>
        <script src="../scripts_js/jquery.mobile-1.3.0.js"></script>
        <script src="../scripts_js/jquery-ui.js"></script>
        <script src="../scripts_js/jquery.ui.touch-punch.js"></script>
        <script>
            $(function() {
                $("#sortable0").sortable({
                    connectWith: ".connectedSortable",
                    revert: true
                }).disableSelection();


            });




        </script>
    </head>
    <body onload="verification_session2();recupererCategories();
                init();
                recupererPictogrammes(0);">
                <div style="right: 5%;  position: fixed; margin-top: 1%;">
                    <label>Categorie: </label>
                <select name="categorie" id="categorie" onchange="categorie()" >
                <option value="0">Tous</option>
            </select> 
                </div>
        <div style="width: 75%; text-align: center; position: fixed; margin-top: 7%; font-size: 250%; " ><p>Placez les pictogrammes dans l'ordre:</p></div>
        <div id="aff_pictos" style=" border: 3px red solid ; height: 90%;  right: 0px;  position: fixed; margin-right: 40px; margin-top: 3%;">
            
            <ul id="sortable0" class="connectedSortable" style="display: inline-block; list-style-type : none ;width: 150px; height: 95%; overflow:auto;">
            </ul>
        </div>
        <script>
            var pic = new Array();
            var idAct = extractUrlParams('id');
            var bd = extractUrlParams('bd');
            var nbPicto = parseInt(extractUrlParams('nb'));
            var width = window.innerWidth / ((nbPicto + 1) * 2);
            var height = window.innerHeight / 6;

            // Ajout des  pictogrames 
            function addPicto(xml) {
                
                var ul = document.getElementById("aff_pictos").getElementsByTagName('ul')[0];
                var tagnom = xml.getElementsByTagName('listeDesPictogrammes');
                var img = tagnom[0].getElementsByTagName('pictogramme');



                for (var i = 0; i < img.length; i++) {

                    var tdli = document.createElement('li');

                    tdli.setAttribute('id', img[i].getElementsByTagName("identifiant")[0].firstChild.nodeValue);
                    var tdNom = tdli.appendChild(document.createElement("img"));
                    tdNom.setAttribute('src', "../imagesPicto/" + img[i].getElementsByTagName('image')[0].firstChild.nodeValue);
                    tdNom.setAttribute('width', (width / 2));
                    tdNom.setAttribute('height', (height / 2));
                    ul.appendChild(tdli);
                }
            }

            //Placement des éléments
            function init() {
                //Affichage des bordures
                var html = document.getElementsByTagName('html')[0];
                if (bd === '2') {
                    html.setAttribute('style', "height: 100%; min-height: 100%; background-image: url(../images/deux_bordures.png); background-position:center; background-repeat:no-repeat; background-size: 100% 100%; -webkit-background-size: 100% 100%; -o-background-size: 100% 100%; -moz-background-size: 100% 100%;");

                }
                else {
                    if (bd === '4') {
                        html.setAttribute('style', "height: 100%; min-height: 100%; background-image: url(../images/quatre_bordures.png); background-position:center; background-repeat:no-repeat; background-size: 100% 100%; -webkit-background-size: 100% 100%; -o-background-size: 100% 100%; -moz-background-size: 100% 100%;");
                    }

                }
                var ul = document.getElementById("aff_pictos").getElementsByTagName('ul')[0];
                var body = document.getElementsByTagName('body')[0];
                ul.setAttribute('style', "display: inline-block; list-style-type : none ;width: " + width + "px; height: 95%; overflow:auto;");

                //Affichage du boutton de validation
                var input = document.createElement('input');
                input.setAttribute('id', "input1");
                input.setAttribute('type', "button");
                input.setAttribute('value', "Valider les pictogrammes");
                input.setAttribute('style', "min-width: " + width + "px; height: " + window.innerHeight / 20 + "px;margin-left: " + window.innerWidth / 2.5 + "px;  margin-top: " + window.innerHeight / 1.3 + "px;position: fixed;");
                input.setAttribute('onclick', "enregistrer();");
                body.appendChild(input);



                // Ajout des carrés pour déposer les pictogrames


                var marge = 50;
                for (var i = 0; i < nbPicto; i++) {
                    var div = document.createElement('div');
                    div.setAttribute('style', "display: inline-block; margin-left: " + marge + "px; margin-top: 20%; border: 5px black solid; width: " + width + "px; height: " + height + "px; position: fixed;");
                    var ul = document.createElement('ul');
                    ul.setAttribute('id', i + "_1");
                    ul.setAttribute('name', 'case');
                    ul.setAttribute('class', "connectedSortable");
                    ul.setAttribute('style', "display: inline-block; list-style-type : none ;width: " + width + "px; height: " + height + "px; margin: 0px;  padding-left: " + (width / 4) + "px; padding-top: " + (height / 4) + "px; border: 0px");

                    marge += (width * 2);
                    div.appendChild(ul);
                    body.appendChild(div);
                    $(function() {
                        $("#" + ul.id).sortable({
                            connectWith: ".connectedSortable",
                            revert: true,
                            receive: function(event, ui) {
                                if (ui.item.closest('ul').children().length === 2) {
                                    $(ui.sender).sortable("cancel");
                                }
                            }

                        }).disableSelection();

                    });
                }
            }

            // Affichage des pictogrammes
            function recupererPictogrammes(c) {
                //suppression des pictogrammes
                var ul = document.getElementById('sortable0');
                while (ul.firstChild) {
                    ul.removeChild(ul.firstChild);
                  }
                  
                var xhr = getXMLHttpRequest();

                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
                        //alert("[" + xhr.responseText + "]");
                        //callback(xhr.responseText);
                        var docXML = xhr.responseText;
                        var listeDesAdultes = stringToXML(docXML);
                        addPicto(listeDesAdultes);
                    }
                };
                if (parseInt(c) === 0) {
                    xhr.open("POST", "../scripts_php/pictogram_recuperer_tous_mysql.php", false);
                    xhr.send(null);
                }
                else {
                    var fd = new FormData();
                    fd.append("categorie", c);

                    xhr.open('POST', "../scripts_php/picto_recuperer_by_cat_mysql.php", false);
                    xhr.send(fd);
                }

            }

            //Vérifie si des cases ne sont pas vide puis enregistre
            function enregistrer() {
               var ul = document.getElementsByName('case');
                for (var i = 0; i < ul.length; i++) {
                    
                    var li = ul[i].getElementsByTagName('li');
                        if (typeof(li[0]) !== "undefined") {                  
                            pic[i] = li[0].id;

                        }
                        else {
                            alert("La case n°" + (i+1)+ " est vide");
                            return;
                        }

					

                }

                //Enregistrement des pictogrammes
                for (var i = 0; i < pic.length; i++) {
                   enregistrer_pictogramme(idAct, pic[i], (i + 1));          
                }
                
                alert("L'activité a bien été ajouté.");
                document.location.href = "../generateur.html";
            }

            //Enregistrement des pictogrammes appartenant à l'activité
            function enregistrer_pictogramme(idAct, idPict, num, emp) {
                //var currentLocation =  document.location.href;
                var xhr = getXMLHttpRequest();

                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
                        //alert("[" + xhr.responseText + "]");
                        //callback(xhr.responseText);
                        var docXML = xhr.responseText;
                    }
                };

                var fd = new FormData();
                fd.append("idAct", idAct);
                fd.append("idPict", idPict);
                fd.append("num", num);
                xhr.open('POST', "../scripts_php/activite_associer_picto_mysql.php", false);
                xhr.send(fd);

            }

            //Extraire les paramètres contenus dans l'url
            function extractUrlParams(nom) {
                var t = location.search.substring(1).split('&');
                for (var i = 0; i < t.length; i++) {
                    var x = t[ i ].split('=');
                    if (x[0] === nom) {
                        return x[1];
                    }
                }
                return null;
            }

            //Récupérer un fichier xml contenant les catégories
            function recupererCategories() {
              
                var xhr = getXMLHttpRequest();
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
                        //alert("[" + xhr.responseText + "]");
                        //callback(xhr.responseText);
                        var docXML = xhr.responseText;
                        var listeDesCategories = stringToXML(docXML);
                        ajouterCategories(listeDesCategories);
                    }
                };

                xhr.open("POST", "../scripts_php/categorie_recuperer_all_mysql.php", false);
                xhr.send(null);
            }
            
            //Ajouter les catégories dans le select
            function ajouterCategories(xml) {
                //
                var select = document.getElementById("categorie");
                var listeDesCats = xml.getElementsByTagName("categorie");

                for (var i = 0; i < listeDesCats.length; i++) {

                    var option = document.createElement("option");
                    option.setAttribute("value", listeDesCats[i].getElementsByTagName("identifiant")[0].childNodes[0].nodeValue);
                    option.appendChild(document.createTextNode(listeDesCats[i].getElementsByTagName("nom")[0].childNodes[0].nodeValue));
                    select.appendChild(option);

                }
            }

            
            function categorie() {
                var indexsite = document.getElementById('categorie');
                recupererPictogrammes(indexsite.options[indexsite.selectedIndex].value);
            }
        </script>
    </body>
</html>